package rhelper

import (
	"github.com/garyburd/redigo/redis"
	"log"
	"time"
)

func newPool(server string, password string) *redis.Pool {
	return &redis.Pool{
		MaxIdle: 3,
		//MaxActive: 20,
		//IdleTimeout: 240 * time.Second,
		IdleTimeout: 0,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", server)
			if err != nil {
				return nil, err
			}

			if password != "" {
				_, err := c.Do("AUTH", password)
				if err != nil {
					c.Close()
					return nil, err
				}
			}

			log.Println("redis tcp connect...")

			return c, err
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
	}
}

var (
	pool *redis.Pool
	//defaultServer = "127.0.0.1:6379"
	//masterAddr    = "127.0.0.1:6379"
	//sentinels = []string{"127.0.0.1:26379", "127.0.0.1:26370", "127.0.0.1:26390"}
)

const (
	ControllerHash     = "purifiers:controller:"
	PurifiersStatus    = "purifiers:status:"
	PurifiersStatusNow = "purifiers:statusnow:"

	// task
	// TaskHash = "w:t:"

	// plan
	PlanHash     = "purifiers:plan:"
	PlanIdHolder = "purifiers:i:pid"
	PlanSort     = "purifiers:sort:"

	// account
	AccountHash = "w:a:"

	UserHash     = "w:u:"
	UserIdHolder = "w:i:uid"

	// message

	MsgHash     = "w:m:"
	MsgURHash   = "w:mu:"
	MsgIdHolder = "w:i:mid"
	// TaskIdHolder = "w:i:tid"

	PowerReport = "purifiers:powerreport:"

	ApnsToken = "purifiers:apns:tk"

	WebAccount = "purifiers:webAcc:"

	EVRelay    = "purifiers:ev:relay:"
	OnlineDev  = "controller:onlinedev"
	OnlineUser = "purifiers:onu:"

	WaitKey = "purifiers:wait:"

	HomeHash = "w:h:"

	ActionHolder = "purifiers:action:c"

	HomeMemberSet       = "w:hm:"
	HomeAdminSortSetMax = 0
	HomeAdminSortSetMin = 0
	HomeIdHolder        = "w:homeidholder"
)

func Pool() *redis.Pool {
	return pool
}

// func init() {
// 	pool = newPool(sentinels, defaultServer)
// 	//initSentinel()
// }

func InitRedis(masterAddr string, password string) {
	if pool != nil {
		pool.Close()
	}

	pool = newPool(masterAddr, password)

}
